package com.szy.news.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.szy.news.service.SyncHttp;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

/**
 * @author qi
 * @date 2014-4-2
 * @name 新闻评价页面
 * 
 */
public class CommentsActivity extends BaseActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comments);

		// 获取传递的数据
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		// 设置标题栏名称
		int nid = bundle.getInt("nid");

		JSONObject dataObject = getComments(0, nid);

		// 获取返回新闻集合
		try {
			JSONArray newslist = dataObject.getJSONArray("commentslist");

			List<HashMap<String, String>> comments = new ArrayList<HashMap<String, String>>();
			for (int i = 0; i < newslist.length(); i++) {
				JSONObject newsObject = (JSONObject) newslist.opt(i);

				HashMap<String, String> hashMap = new HashMap<String, String>();
				hashMap.put("commentator_from", newsObject.getString("region"));
				hashMap.put("comment_ptime", newsObject.getString("ptime"));
				hashMap.put("comment_content", newsObject.getString("content"));
				comments.add(hashMap);
			}
			SimpleAdapter commentsAdapter = new SimpleAdapter(this, comments,
					R.layout.comments_list_item, new String[] {
							"commentator_from", "comment_ptime",
							"comment_content" }, new int[] {
							R.id.commentator_from, R.id.comment_ptime,
							R.id.comment_content });

			ListView commentsList = (ListView) findViewById(R.id.comments_list);
			commentsList.setAdapter(commentsAdapter);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取新闻详细信息
	 * 
	 * @return
	 */
	private JSONObject getComments(int startnid, int nid) {
		JSONObject dataObject = new JSONObject();
		SyncHttp syncHttp = new SyncHttp();
		String url = getString(R.string.url) + getString(R.string.getComments);
		String params = "startnid=" + startnid + "&count="
				+ getString(R.string.comments_count) + "&nid=" + nid;
		try {
			String retString = syncHttp.httpGet(url, params);
			JSONObject jsonObject = new JSONObject(retString);
			// 获取返回码，0表示成功
			int retCode = jsonObject.getInt("ret");
			if (0 == retCode) {
				dataObject = jsonObject.getJSONObject("data");
			}

		} catch (Exception e) {
			// e.printStackTrace(); 网络连接失败
			System.out.println(R.string.Connet_failure);
		}
		return dataObject;
	}
}
